package com.xywl.escort.view.pwd

import android.os.Bundle
import android.os.CountDownTimer
import android.text.TextUtils
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.trello.rxlifecycle2.LifecycleTransformer
import com.xywl.escort.R
import com.xywl.escort.base.BaseActivity
import com.xywl.escort.bean.*
import com.xywl.escort.common.Constant
import com.xywl.escort.common.Constant.EventMessage.FINISH_ACTIVITY
import com.xywl.escort.common.Constant.EventType.EVENT_MODIFY_LOGIN_PWD_TYPE
import com.xywl.escort.common.PreferenceKeys
import com.xywl.escort.common.PreferenceKeys.PHONE
import com.xywl.escort.common.PreferenceKeys.TOKEN
import com.xywl.escort.utils.MD5
import com.xywl.escort.utils.RegexUtils
import com.xywl.escort.utils.RxSPTool
import com.xywl.escort.utils.ToastUtil
import com.xywl.escort.widget.GlideApp
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_recover_pwd.*
import org.greenrobot.eventbus.EventBus
import timber.log.Timber
import java.util.regex.Pattern
import javax.inject.Inject

@Route(path = "/xy/pwd/recover")
class RecoverPwdActivity : BaseActivity(), RecoverPwdContract.View {
    private var isCountDown: Boolean = false
    private var captchaKey = ""
    @Inject
    lateinit var mPresenter: RecoverPwdContract.Presenter

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_recover_pwd)
        ARouter.getInstance().inject(this)

        val token = RxSPTool.getString(this@RecoverPwdActivity, TOKEN)
        initView(token)
        addListener(token)
    }

    private fun initView(token: String) {
        showBackButton()
        mPresenter.takeView(this)
        mPresenter.getCaptcha()

        Timber.tag("RecoverPwdActivity").e("找回登录密码")
        setTitleText(R.string.setting_recover_pwd)

        if (TextUtils.isEmpty(token)) {
            edit_phone.visibility = View.VISIBLE
        }
    }

    private fun addListener(token: String) {
        text_send_ver_code.setOnClickListener {
            getCode(token)
        }

        btn_confirm.setOnClickListener {
            submit(token)
        }

        text_send_img_code.setOnClickListener {
            mPresenter.getCaptcha()
        }
    }

    private fun getCode(token: String) {
        val imgCode = edit_msg_img_code.text.toString().trim()
        if (TextUtils.isEmpty(token)) {
            val phone = edit_phone.text.toString().trim()
            if (!RegexUtils.checkMobile(phone)) {
                ToastUtil.showTip(this, R.string.user_error_hint_phone)
                return
            }
            if (!isCountDown && checkCaptchaCode(imgCode)) {
                val req = GetSmsCodeReq()
                req.phone = phone
                req.operateType = 5
                req.captchaCode = imgCode
                req.captchaKey = captchaKey
                mPresenter.getCode(req)
            }
        } else {
            val phone = RxSPTool.getString(this, PHONE)
            if (!RegexUtils.checkMobile(phone)) {
                ToastUtil.showTip(this, "用户登录信息失效，请重新登录")
                return
            }
            if (!isCountDown && checkCaptchaCode(imgCode)) {
                val req = GetSmsCodeReq()
                req.phone = phone
                req.operateType = 5
                req.captchaCode = imgCode
                req.captchaKey = captchaKey
                mPresenter.getCode(req)
            }
        }
    }

    private fun submit(token: String) {
        val newPwd = edit_new_pwd.text.toString().trim()
        val confirmPwd = edit_confirm_pwd.text.toString().trim()
        val code = edit_msg_ver_code.text.toString().trim()
        val imgCode = edit_msg_img_code.text.toString().trim()
        var phone = ""
        if (TextUtils.isEmpty(token)) {
            phone = edit_phone.text.toString().trim()
        } else {
            phone = RxSPTool.getString(this, PHONE)
        }
        if (!RegexUtils.checkMobile(phone)) {
            ToastUtil.showTip(this, R.string.user_error_hint_phone)
            return
        }
        if (checkAccount(phone) && checkCode(code, imgCode) && checkPwd(newPwd, confirmPwd)) {
            // TODO 重置登录密码
            val password = MD5.encrypt(newPwd)
            val req = ForgetPwdReq()
            req.account = phone
            req.pwd = password
            req.smsCode = code
            req.captchaCode = imgCode
            req.captchaKey = captchaKey
            mPresenter.recoverLoginPwd(req)
        }
    }

    private fun checkPwd(pwd: String, confirmPwd: String): Boolean {
        val regex = "^(?=.*[a-zA-Z])(?=.*[0-9])[0-9A-Za-z!@~#\$%^&*()-+_`~,./=?\\\\|]{8,20}\$"
        if (TextUtils.isEmpty(pwd)) {
            ToastUtil.showTip(this, R.string.user_account_hint_password)
            return false
        } else if (pwd.length < Constant.Length.MIN_LOGIN_PWD_LENGTH) {
            ToastUtil.showTip(this, R.string.user_account_reset_password_error)
            return false
        } else if (TextUtils.isEmpty(confirmPwd)) {
            ToastUtil.showTip(this, R.string.user_account_hint_password)
            return false
        } else if (pwd != confirmPwd) {
            ToastUtil.showTip(this, "密码输入不一致")
            return false
        } else if (!Pattern.matches(regex, pwd)) {
            ToastUtil.showTip(this, R.string.user_password_format_error)
            return false
        }
        return true
    }

    private fun checkAccount(account: String): Boolean {
        if (TextUtils.isEmpty(account)) {
            ToastUtil.showTip(this, R.string.user_error_hint_phone)
            return false
        }
        return true
    }

    private fun checkCaptchaCode(imgCode: String): Boolean {
        if (TextUtils.isEmpty(imgCode)) {
            ToastUtil.showTip(this, R.string.user_img_code_empty)
            return false
        }
        return true
    }

    private fun checkCode(smsCode: String, imgCode: String): Boolean {
        if (TextUtils.isEmpty(smsCode)) {
            ToastUtil.showTip(this, R.string.user_sms_code_empty)
            return false
        }
        if (TextUtils.isEmpty(imgCode)) {
            ToastUtil.showTip(this, R.string.user_img_code_empty)
            return false
        }
        return true
    }

    private var mVerificationTimer = object : CountDownTimer((60 * 1000).toLong(), 1000) {
        override fun onTick(millisUntilFinished: Long) {
            text_send_ver_code.isEnabled = false
            text_send_ver_code.text = getString(R.string.account_auth_cd_format, millisUntilFinished / 1000)
        }

        override fun onFinish() {
            text_send_ver_code.isEnabled = true
            text_send_ver_code.text = getString(R.string.account_auth_re_get)
            isCountDown = false
        }
    }

    override fun isActive(): Boolean {
        return false
    }

    override fun <T> bindToLife(): LifecycleTransformer<T> {
        return this.bindToLifecycle()
    }

    override fun startCountDown() {
        isCountDown = true
        text_send_ver_code.isEnabled = false
        mVerificationTimer.start()
    }

    override fun getCodeFailure(msg: String?) {
        ToastUtil.showTip(this, msg)
        Timber.tag("RecoverPwdActivity").e("getCodeFailure msg=$msg")
    }

    override fun getCaptchaSuccess(bean: CaptchaBean?) {
        Timber.e("getCaptchaSuccess")
        if (null != bean) {
            val bitmap = bean.bitmap
            captchaKey = bean.captchaKey
            GlideApp.with(this)
                    .load(bitmap)
                    .centerCrop()
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .skipMemoryCache(true)
                    .placeholder(R.mipmap.icon_default_picture)
                    .into(img_code)
        }
    }

    override fun getCaptchaFailure() {
        Timber.e("getCaptchaFailure")
    }

    override fun recoverLoginSuccess(resp: BaseResp?) {
        ToastUtil.showTip(this, "重置登录密码成功")
        clearUserInfo()

        EventBus.getDefault().post(MessageEvent(EVENT_MODIFY_LOGIN_PWD_TYPE, FINISH_ACTIVITY))
        finish()
    }

    override fun recoverLoginFailure(msg: String) {
        ToastUtil.showTip(this, msg)
    }

    private fun clearUserInfo() {
        RxSPTool.clearPreference(this, PreferenceKeys.USER_ID)
        RxSPTool.clearPreference(this, TOKEN)
        RxSPTool.clearPreference(this, PHONE)
        RxSPTool.clearPreference(this, PreferenceKeys.NICK_NAME)
        RxSPTool.clearPreference(this, PreferenceKeys.HEAD_IMG)
    }

    override fun onBackPressed() {
        super.onBackPressed()
        mVerificationTimer.onFinish()
        mVerificationTimer.cancel()
    }

    override fun onDestroy() {
        super.onDestroy()
        mPresenter.unSubscribe()
        mVerificationTimer.onFinish()
        mVerificationTimer.cancel()
    }
}
